//
//  AppDelegate.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/19.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "AppDelegate.h"
#import "LoadingVC.h"
#import "LoginVC.h"
#import "BaseNavigationController.h"
#import "MainTabBarVC.h"
#import "IMManager.h"
#import <Bagel.h>
#import "YBApiManager+Login.h"
#import <UserNotifications/UserNotifications.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <YYText/YYText.h>
#import "UIImage+Gradient.h"


@interface AppDelegate ()
@property (nonatomic, assign) UIBackgroundTaskIdentifier bgID;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self configAppearance];
    [self configThirdTools];
    [kUsermanager isLogin];
    [[IMManager shareManager] connect];
    
    [self registPush];
//    [Bagel start];
    [self getNewestVersionInfo];
    return YES;
}
- (void)registPush {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//    center.delegate = self;
    [center requestAuthorizationWithOptions:( UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"request authorization succeeded!");
        }
    }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    self.bgID = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:self.bgID];
    }];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



#pragma mark - 配置信息
- (void)configThirdTools {
//    [WXApi registerApp:@"wx7f75e5900be52eff"];
    [[IQKeyboardManager sharedManager] registerTextFieldViewClass:YYTextView.class didBeginEditingNotificationName:YYTextViewTextDidBeginEditingNotification didEndEditingNotificationName:YYTextViewTextDidEndEditingNotification];
}
- (void)configAppearance {
//    UIImage *redImg = UIImage.k_imgFillColor(UIColor.redColor, CGSizeMake(ScreenWidth, NavigationBarHeight));
//    [[UINavigationBar appearance] setBackgroundImage:redImg forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [[UIBarButtonItem appearance] setTintColor:UIColor.whiteColor];
    [UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName: UIColor.whiteColor};
    UIImage *btnBackgroundImg = [[UIImage new] createImageWithSize:CGSizeMake(ScreenWidth, NavigationBarHeight) gradientColors:@[UIColor.k_hexColor(0x6BA4FE), UIColor.k_hexColor(0x3A85F9)] percentage:@[@0.0,@1.0] gradientType:GradientFromLeftToRight];
    [[UINavigationBar appearance] setBackgroundImage:btnBackgroundImg forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setShadowImage:UIImage.k_imgFillColor(UIColor.clearColor, CGSizeMake(ScreenWidth, 0.5))];
    UIImage *clearImg = [UIImage new];
    [[UISearchBar appearance] setBackgroundImage:clearImg forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
//    [[UISearchBar appearance] setBackgroundColor:UIColor.whiteColor];
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTitle:@"取消"];
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.k_t2Color} forState:UIControlStateNormal];

//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.k_t2Color} forState:UIControlStateNormal];
//    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.redColor} forState:UIControlStateSelected];
    
    [UIColor setTextColor_mainColor:UIColor.k_hexColor(0x3A85F9) _secondColor:UIColor.k_hexColor(0x333333) _thirdColor:UIColor.k_hexColor(0x666666) _placeholderColor:UIColor.k_hexColor(0x999999)];
    
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal ];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState: UIControlStateHighlighted];
}



- (void)enterLoadingVC {
    self.window.rootViewController = [LoadingVC new];
    [self.window makeKeyAndVisible];
}
- (void)enterLoginVC {
    LoginVC *vc = LoginVC.new;
    BaseNavigationController *navi = [[BaseNavigationController alloc] initWithRootViewController:vc];
    self.window.rootViewController = navi;
    [self.window makeKeyAndVisible];
}
- (void)enterHomeVC {
    self.window.rootViewController = [[MainTabBarVC alloc] init];
    [self.window makeKeyAndVisible];
}
- (void)getNewestVersionInfo {
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[[YBApiManager shareManager] getNewestVersion] subscribeNext:^(id  _Nullable x) {
            @strongify(self);
            NSDictionary *dataDic = [[x objectForKey:@"data"] mj_JSONObject];
            if ([dataDic isKindOfClass:NSDictionary.class]) {
                [self isNeedUpdateVersionWithDataDic:dataDic];
            }
            
        } error:^(NSError * _Nullable error) {
            
        }];
    });
}

/**
 是否有新版本需要更新 （替换kAppID  为对应的APPID）
 
 @return 返回布尔值
 */
- (BOOL)isNeedUpdateVersionWithDataDic:(NSDictionary *)dataDic {
    NSInteger newVersion = [[dataDic objectForKey:@"newversion"] integerValue];
    NSInteger currentVersion = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] integerValue];  //获取本地版本号
    //  1.0  1.1
    if (currentVersion < newVersion) {
        //  提示升级app
        NSArray *btns = @[@"取消", @"更新"];
//        if ([dataDic[@"versionForce"] integerValue] == 1) {
//            btns = @[@"更新"];
//        }
        [LBXAlertAction showAlertWithTitle:@"版本更新提示" msg:dataDic[@"content"]?:@"" buttonsStatement:btns chooseBlock:^(NSInteger buttonIdx) {
            
            //            NSString *urlStr = @"itms-apps://itunes.apple.com/cn/app/id1463359092";
            if (buttonIdx == 1 || btns.count <= 1) {
                NSString *urlStr = [dataDic objectForKey:@"downloadurl"];
                [[UIApplication sharedApplication] openURL:urlStr.toURL options:@{UIApplicationOpenURLOptionsSourceApplicationKey: @YES} completionHandler:nil];
                
            }
        }];
        return YES;
    } else {
        
        
    }
    return NO;
}

@end
